package com.mask.juc.v1.c_011_interview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 淘宝面试题
 * 实现一个容器，提供两个方法，add、size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 * @author hx
 * @date 2021/10/13 12:09 下午
 */

public class NotifyHoldingLock {
    //保证线程的可见性
//    volatile List lists = new ArrayList();
    volatile List lists = Collections.synchronizedList(new ArrayList<>());
    public void add(Object o){
        lists.add(o);
    }

    public int size(){
        return lists.size();
    }

    public static void main(String[] args) {
        NotifyHoldingLock c = new NotifyHoldingLock();
        final Object lock = new Object();
        new Thread(() -> {
            synchronized (lock){
                System.out.println("t2启动");
                if (c.size() != 5){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 结束");
            }
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");
            synchronized (lock){
                for (int i  = 0; i < 10; i++) {
                    c.add(new Object());
                    System.out.println("add " + i);
                    if (c.size() == 5){
                        lock.notify(); //不释放锁
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1").start();



    }
}
